package service;

import java.io.IOException;
import java.util.ArrayList;

import main.ThreadRunner;

import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import util.FileLoader;
import crawler.CrawlerDocument;
import crawler.DocumentPool;

public class FetchService implements Daemon {
	
	private final Logger logger = Logger.getLogger(FetchService.class);
	private static GlobalConfiguration config = GlobalConfiguration.getInstance();

	public FetchService() {
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}	
	@Override
	public void init(DaemonContext args) throws DaemonInitException, Exception {	
		String logConf = config.get("log4j");
		PropertyConfigurator.configure(logConf);
		logger.info("Initializing ...");
	}

	@Override
	public void start() throws Exception {
		
		logger.info("Starting...");
		
		String seedFile = config.get("seed");
		
		DocumentPool urlPool = new DocumentPool();
		DocumentPool docPool = new DocumentPool();

		ArrayList<CrawlerDocument> seedlist = null;
		
		try {
			 seedlist = FileLoader.LoadSeed(seedFile);
		} catch (IOException e) {
			logger.error("{}", e);
		}
		
		Allocator allocator = new Allocator(urlPool);
		
		allocator.addSeedlist(seedlist);

		Thread allocatorThread = new Thread(allocator);
		
		logger.info("Allocator thread.");
		
		Thread fetcherThread = new Thread(new Fetcher(urlPool, docPool));
		
		logger.info("Fetch thread.");
		
		Thread indexThread = new Thread(new Indexer(docPool));
		
		logger.info("Indexer Thread");

		//Thread dumpThread = new Thread(Dumper.getInstance());
		
		//logger.info("Dump thread.");
		
		allocatorThread.start();
		
		//dumpThread.start();

		fetcherThread.start();	
		
		indexThread.start();
		
		logger.info("All thread started.");
	}

	@Override
	public void stop() throws Exception {
	}
	

}
